<template>
  <el-form
    ref="formRef"
    require-asterisk-position="right"
    label-position="top"
    :model="state"
    :rules="rules"
  >
    <domain-input v-model="state.domains" has-label />
    <el-form-item v-if="$slots.rrsSwitch" label="同步添加解析记录" class="mb-6">
      <slot name="rrsSwitch"></slot>
    </el-form-item>
    <log-input-table v-if="hasTable" :form-state="state" label="解析记录" />
  </el-form>
  <div class="pt-[14px] submit-btn">
    <el-divider class="m-0" />
    <el-button
      :loading="loading"
      :disabled="!domainTotal"
      class="mt-4 mb-6 w-[74px]"
      type="primary"
      @click="handleSubmit"
      >添加</el-button
    >
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import { useDomainsTotal } from '../hooks/useDomainsTotal'
import type { RrsItem } from '../type'
import { useDomainAddRules } from '../utils/rules/domainAdd'
import DomainInput from './DomainInput.vue'
import LogInputTable from './LogInputTable.vue'

interface IProps {
  mainSubmit?: () => Promise<void>
  loading: boolean
  hasTable?: boolean
  formState: {
    domains: string
    rrs: RrsItem[]
  }
}

interface IEmits {
  (event: 'submit'): void
}

const props = withDefaults(defineProps<IProps>(), { hasTable: true })
const emit = defineEmits<IEmits>()

const state = computed(() => props.formState)
const formRef = ref<FormInstance>()

const { rules } = useDomainAddRules(state, formRef)

const domainTotal = useDomainsTotal(() => props.formState.domains)

async function handleSubmit() {
  await formRef.value?.validateField('rrsMain')
  await formRef.value?.validate()

  emit('submit')
  await props.mainSubmit?.()
}

defineExpose({
  submit: handleSubmit
})
</script>

<style lang="scss" scoped>
.el-form {
  :deep(.el-form-item__label) {
    pointer-events: none;
  }
}
</style>
